package com.hengyue.system.repository;

import com.hengyue.common.core.respository.BaseRepository;
import com.hengyue.system.domain.entity.SysDept;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface DeptRepository extends BaseRepository<SysDept, Long> {

    boolean existsByParentIdAndDelFlag(Long parentId, String delFlag);

    boolean existsByParentIdAndStatusAndDelFlag(Long parentId, String status, String delFlag);

    List<SysDept> findByParentId(Long parentId);

    List<SysDept> findAllByAncestorsLike(String ancestors);

    @Modifying
    @Query("UPDATE SysDept d SET d.delFlag = :delFlag WHERE d.id = :id")
    void updateDelFlagById(@Param("id") Long id, @Param("delFlag") String delFlag);

    @Modifying
    @Query("UPDATE SysDept d SET d.ancestors = REPLACE(d.ancestors, :oldAncestors, :newAncestors) " +
            "WHERE d.ancestors LIKE :ancestorPattern" + "%")
    void updateAncestorsForChildren(
            @Param("ancestorPattern") String ancestorPattern,
            @Param("oldAncestors") String oldAncestors,
            @Param("newAncestors") String newAncestors
    );

}